﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Brainee.Search;

namespace Brainee.Examples.Search
{
  public partial class EightQueensControl : UserControl
  {
    private PathSolution _solution;

    public EightQueensControl ()
    {
      InitializeComponent ();
    }

    public PathSolution Solution 
    {
      get { return _solution; }
      set
      {
        _solution = value;
        this.SafeUICall(c => c.Refresh ());
      }
    }

    private void OnPaint (object sender, PaintEventArgs e)
    {
      // Fill BackGround
      using (Brush back= new SolidBrush (this.BackColor))
      {
        e.Graphics.FillRectangle (back, this.ClientRectangle);
      }

      // Paint board
      int padding = 16;
      int squareSize = (((Width < Height) ? Width : Height) - 2 * padding) / 8;
      int marginL = (Width - 8 * squareSize) / 2;
      int marginR = Width - (marginL + 8 * squareSize);
      int marginT = (Height - 8 * squareSize) / 2;
      int marginB = Height - (marginT + 8 * squareSize);

      for (int y = marginT; y < Height - marginB; y += squareSize)
      {
        for (int x = marginL; x < Width - marginR; x += squareSize)
        {
          Rectangle square = new Rectangle (x, y, squareSize, squareSize);
          Brush color = ((x - marginL) % (2 * squareSize) == (y - marginT) % (2 * squareSize)) ? Brushes.White : Brushes.Black;
          e.Graphics.FillRectangle (color, square);
        }
      }

      // Paint queens
      if (Solution != null)
      {
        int[,] board = ((EightQueens.State)Solution.States.Last ()).Board;
        for (int y = 0; y < 8; y ++)
        {
          for (int x = 0; x < 8; x ++)
          {
            Brush color = (x % 2 == y % 2) ? Brushes.White : Brushes.Black;

            Rectangle square = new Rectangle (marginL + x*squareSize, marginT + y*squareSize, squareSize, squareSize);
            e.Graphics.FillRectangle (color, square);

            if (board [y, x] == 1)
            {
              color = Brushes.Gray;
              Rectangle queen = new Rectangle (square.Left + squareSize / 4, square.Top + squareSize / 4, squareSize / 2, squareSize / 2);
              e.Graphics.FillEllipse (color, queen);
            }
          }
        }
      }
    }

    private void ProblemControl_Resize (object sender, EventArgs e)
    {
      Refresh ();
    }
  }
}
